package com.cp.admin.core.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;

import java.io.BufferedReader;
import java.io.InputStreamReader;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Set;

/**
 * @Description ：
 * @Author ： mx.li
 * @Date ： 2019/01/24 22:41
 */
public class HttpUrlUtils {

    public static void main(String[] args) {
        // 此处需要传递的3个参数，必填项
        String name = "cqssc";// 彩种
        String uid = "1153349";// 用户ID
        String token = "6dc664246297131b3408d5b0d21a97b98d73e02a";// token
        String date="20190101";
        String order="sort";
        String num="1";

        String url = "http://api.caipiaokong.com/lottery/";
        url += "?name=" + name;
        url += "&format=json";// 数据格式，此文件仅支持json
        url += "&uid=" + uid;
        url += "&token=" + token;
        url += "&date=" + date;
        url += "&order=" + order;
        url += "&num=" + num;

        String urlAll = new StringBuffer(url).toString();
        String charset = "UTF-8";
        String jsonResult = get(urlAll, charset);// 得到JSON字符串
        System.out.println(jsonResult);
        JSONObject object = JSON.parseObject(jsonResult);// 转化为JSON类
        try {
            Set<String> it = object.keySet();
            for (String key : it){
                System.out.println("---->key:" + key);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }



    /**
     *
     * @param urlAll:请求接口
     * @param charset:字符编码
     * @return 返回json结果
     */
    public static String get(String urlAll, String charset) {
        BufferedReader reader = null;
        String result = null;
        StringBuffer sbf = new StringBuffer();
        String userAgent = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.66 Safari/537.36";// 模拟浏览器
        try {
            URL url = new URL(urlAll);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setReadTimeout(30000);
            connection.setConnectTimeout(30000);
            connection.setRequestProperty("User-agent", userAgent);
            connection.connect();
            InputStream is = connection.getInputStream();
            reader = new BufferedReader(new InputStreamReader(is, charset));
            String strRead = null;
            while ((strRead = reader.readLine()) != null) {
                sbf.append(strRead);
                sbf.append("\r\n");
            }
            reader.close();
            result = sbf.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
}
